package com.wzt.lianfirecontrol.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentTransaction;

import com.mob.pushsdk.MobPush;
import com.wzt.lianfirecontrol.App;
import com.wzt.lianfirecontrol.R;
import com.wzt.lianfirecontrol.bean.BaseModel;
import com.wzt.lianfirecontrol.bean.ConstData;
import com.wzt.lianfirecontrol.bean.MessageEvent;
import com.wzt.lianfirecontrol.bean.recode.BannerModel;
import com.wzt.lianfirecontrol.bean.recode.home.jiankong.JianKongDeviceModel;
import com.wzt.lianfirecontrol.dao.MyHandler;
import com.wzt.lianfirecontrol.fragment.BaseFragment;
import com.wzt.lianfirecontrol.fragment.InfoListFragment;
import com.wzt.lianfirecontrol.http.HttpHelper;
import com.wzt.lianfirecontrol.http.Url;
import com.wzt.lianfirecontrol.http.json.ParseJsonData;
import com.wzt.lianfirecontrol.lecheng.PlayLeChengActivity;
import com.wzt.lianfirecontrol.lecheng.PlayVideoActivity;
import com.wzt.lianfirecontrol.lecheng.PlayYingShiActivity;
import com.wzt.lianfirecontrol.manager.SystemBarTintManager;
import com.wzt.lianfirecontrol.utils.DialogUtils;
import com.wzt.lianfirecontrol.utils.JSONUtil;
import com.wzt.lianfirecontrol.utils.ScreenUtils;
import com.wzt.lianfirecontrol.utils.SpUtils;
import com.wzt.lianfirecontrol.utils.StringUtils;
import com.wzt.lianfirecontrol.utils.ToastUtils;
import com.wzt.lianfirecontrol.utils.Utils;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.bean.ZxingConfig;
import com.yzq.zxinglibrary.common.Constant;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.HashMap;

public class BaseActivity extends AppCompatActivity {

    private BaseFragment mCurrentBaseFragment;

    // 上次点击动作时间
    private long lastClickTime = 0;
    // 是否正在刷新
    public boolean isRefreshing = false;

    private static final int REQUEST_CODE_SCAN = 1;// 跳转到扫一扫页面

    protected MyHandler handler;

    private Dialog sqCodeContentDialog;

    public boolean isExitLogin = false;
    private String mMessage;
    private VNRPlayHttpHelper mVnrPlayHttpHelper;

    // private static final int NVRPLAY = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        EventBus.getDefault().register(this);

        handler = new MyHandler(this) {

            @Override
            public void dealWithMsg(Message msg) {
                // TODO Auto-generated method stub
                dealWithMyMsgs(msg);
            }
        };
        ActivityCollecter.addActivity(this);
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }
        MobPush.setBadgeCounts(0);
    }


    protected void dealWithMyMsgs(Message msg) {
    }

    /**
     * 点击动作汇总
     *
     * @param baseModel
     */
    public void setClickAction(BaseModel baseModel) {
        setClickAction(baseModel, null);
    }

    public void setClickAction(String actionType, String actionValue, String actionTitle, HashMap<String, String> hashMap) {
        setClickAction(actionType, actionValue, actionTitle, hashMap, null);
    }

    public void setClickAction(String actionType, String actionValue, String actionTitle, HashMap<String, String> hashMap, Bundle bundle) {
        BannerModel bannerModel = new BannerModel();
        bannerModel.setActionTitle(actionTitle);
        bannerModel.setActionType(actionType);
        bannerModel.setActionValue(actionValue);
        if (null == bundle) {
            bundle = new Bundle();
        }
        HashMap<String, String> url_params = null;
        if (bundle.containsKey(ConstData.ACTIONPARAMS)) {
            url_params = (HashMap<String, String>) bundle.getSerializable(ConstData.ACTIONPARAMS);
        }
        if (null == hashMap) {
            hashMap = new HashMap<>();
        }
        if (null != url_params) {
            hashMap.putAll(url_params);
        }
        bannerModel.setActionParams(hashMap);
        setClickAction(bannerModel, bundle);
    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void Event(MessageEvent messageEvent) {
//        mMessage = messageEvent.getMessage();
//    }
    /**
     * 点击动作汇总
     *
     * @param baseModel
     */
    public void setClickAction(BaseModel baseModel, Bundle skipBundle) {
        if (null == baseModel) {
            return;
        }
        String actionType = baseModel.getActionType();
        String actionValue = baseModel.getActionValue();
        if (StringUtils.isEmpty(actionType)) {
            return;
        }
        if (null == skipBundle) {
            skipBundle = new Bundle();
        }
        skipBundle.putString(ConstData.ACTIONTITLE, baseModel.getActionTitle());
        skipBundle.putString(ConstData.ACTIONVALUE, baseModel.getActionValue());
        skipBundle.putSerializable(ConstData.ACTIONPARAMS, baseModel.getActionParams());
        skipBundle.putSerializable(ConstData.ACTIONMODLE, baseModel);





        switch (actionType) {
            // 跳转到网页
            case ConstData.WEB:

                if (!StringUtils.isEmpty(actionValue)) {
                    skipBundle.putString(ConstData.URL, actionValue);
                    openActivity(WebActivity.class, skipBundle, 0);
                }

                break;
            case ConstData.WEB_CAD:

                openActivity(WebCadActivity.class, skipBundle, 0);
                break;
            case ConstData.SHOWFRAG:
                // 跳转故障
                openActivity(ShowFragActivity.class, skipBundle, 0);
                break;
            // 通过页面路径跳转
            case ConstData.PAGE_PATH:
                skipToTargetActivityByName(actionValue, baseModel.getActionParams(), skipBundle);
                break;
            // 跳转到扫一扫页面
            case ConstData.SQCODE:
                skipToSqCode(null);
                break;
            //  拨打电话
            case ConstData.PHONE:
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + actionValue));
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
                break;
            // 监控播放
            case ConstData.VIDEO:
                switch (actionValue) {

                    case "1":  // easyVNR
                        JianKongDeviceModel jianKongDeviceModel = (JianKongDeviceModel) skipBundle.getSerializable("JianKongDeviceModel");
                        if (jianKongDeviceModel.getStreamUrl()!= null) {
                            SpUtils.putString(BaseActivity.this, "StreamUrl1", jianKongDeviceModel.getStreamUrl());
                            String channelNo = jianKongDeviceModel.getChannelNo();
                            String ip = jianKongDeviceModel.getIp();
                            String port = jianKongDeviceModel.getPort();
                            initVNRPlayHttpHelper1(ip, port, channelNo);
                        }




                        break;
                    case "2":         // 萤石
                        openActivity(PlayYingShiActivity.class, skipBundle, 0);
                        break;
                    case "3":         // 乐橙
                        openActivity(PlayLeChengActivity.class, skipBundle, 0);
                        break;
                    default:
                        // 矩阵接入
                        JianKongDeviceModel jianKongDeviceModel2 = (JianKongDeviceModel) skipBundle.getSerializable("JianKongDeviceModel");
                        if (jianKongDeviceModel2.getStreamUrl()!= null) {
                            SpUtils.putString(BaseActivity.this, "StreamUrl", jianKongDeviceModel2.getStreamUrl());

                            String channelNo = jianKongDeviceModel2.getChannelNo();
                            String ip = jianKongDeviceModel2.getIp();
                            String port = jianKongDeviceModel2.getPort();
                            initVNRPlayHttpHelper4(ip, port, channelNo);
                        }


                        break;
                }
                break;
        }
    }
    private static final int NVRPLAY = 1;
    private void initVNRPlayHttpHelper1(String ip, String port, String channelNo) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("ip", ip);
        hashMap.put("port", port);
        hashMap.put("channelNo", channelNo);
        Log.e("ip",ip);
        Log.e("port",port);
        Log.e("channelNo",channelNo);
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        Log.e("JSONOBJECT",JSONUtil.mapToJSonStr(hashMap));
        mVnrPlayHttpHelper = new VNRPlayHttpHelper(BaseActivity.this, Url.EasyNVRTouch, NVRPLAY, handler, true, url_params);
        mVnrPlayHttpHelper.setParseJsonData(new VNRPlayParseJsonData());
        mVnrPlayHttpHelper.getHttpRequest(true);
    }



    // 需要检查

    private static final int NVRPLAY_What = 4;
    private void initVNRPlayHttpHelper4(String ip, String port, String channelNo) {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("ip", ip);
        hashMap.put("port", port);
        hashMap.put("channelNo", channelNo);
        Log.e("ip",ip);
        Log.e("port",port);
        Log.e("channelNo",channelNo);
        HashMap<String, String> url_params = new HashMap<>();
        url_params.put(ConstData.JSONOBJECT, JSONUtil.mapToJSonStr(hashMap));
        Log.e("JSONOBJECT",JSONUtil.mapToJSonStr(hashMap));
        mVnrPlayHttpHelper = new VNRPlayHttpHelper(BaseActivity.this, Url.NVRPLAY, NVRPLAY_What, handler, true, url_params);
        mVnrPlayHttpHelper.setParseJsonData(new VNRPlayParseJsonData());
        mVnrPlayHttpHelper.getHttpRequest(true);
    }

    class VNRPlayHttpHelper extends HttpHelper {

        public VNRPlayHttpHelper(BaseActivity activity, String url, int what, Handler handler, boolean isPost, HashMap<String, String> params) {
            super(activity, url, what, handler, isPost, params);
        }

    }
    protected class VNRPlayParseJsonData extends ParseJsonData {

        public VNRPlayParseJsonData() {
        }

        @Override
        public void analyzeResult(String dataStr, Bundle bundle, int what) {

            switch (what) {
                case NVRPLAY_What:
                    String streamUrl = SpUtils.getString(BaseActivity.this, "StreamUrl", "");
                    Bundle bundle1 = new Bundle();
                    bundle1.putString("url", streamUrl);
                    openActivity(PlayVideoActivity.class, bundle1, 0);
                    break;
                case NVRPLAY:
                    String streamUrl1 = SpUtils.getString(BaseActivity.this, "StreamUrl1", "");
                    Bundle bundle2 = new Bundle();
                    bundle2.putString("url", streamUrl1);
                    openActivity(PlayVideoActivity.class, bundle2, 0);
                    break;

            }
        }

    }

    /**
     * 通过activity的名打开activity
     *
     * @param activityName
     * @param params
     */
    private void skipToTargetActivityByName(String activityName, HashMap<String, String> params, Bundle bundle) {
        try {
            if (null == bundle) {
                bundle = new Bundle();
            }
            if (null == params) {
                params = new HashMap<>();
            }
            Class targetClass = Class.forName(activityName);
            for (String key : params.keySet()) {
                bundle.putString(key, params.get(key));
            }
            openActivity(targetClass, bundle, 0);
        } catch (Exception e) {
        }
    }

    /**
     * 打开一个activity
     *
     * @param mClass
     */
    public void openActivity(Class<?> mClass) {
        openActivity(mClass, new Bundle(), 0);
    }

    /**
     * 打开一个activity
     *
     * @param mClass
     * @param bundle
     * @param resquestCode
     */
    public void openActivity(Class<?> mClass, Bundle bundle, int resquestCode) {
        Intent intent = new Intent(this, mClass);
        if (null != bundle) {
            intent.putExtras(bundle);
        }
        if (0 == resquestCode) {
            startActivity(intent);
        } else {
            startActivityForResult(intent, resquestCode);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SCAN:
                if (resultCode == -1) {
                    if (data != null) {
                        String content = data.getStringExtra(Constant.CODED_CONTENT);
                        if (!StringUtils.isEmpty(content)) {
                            // 扫描二维码成功方法
                            if (content.startsWith("http")) {
                                BannerModel bannerModel = new BannerModel();
                                bannerModel.setActionType(ConstData.WEB);
                                bannerModel.setActionValue(content);
                                setClickAction(bannerModel);
                            } else {
                                sqCodeContentDialog = DialogUtils.createSureAndCancelDialog(this,
                                        "扫描结果", content, "取消", "复制", new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                DialogUtils.closeDialog(sqCodeContentDialog);
                                            }
                                        }, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                Utils.copyToClipBoard(BaseActivity.this, content, "复制成功");
                                                DialogUtils.closeDialog(sqCodeContentDialog);
                                            }
                                        });
                                DialogUtils.showDialog(sqCodeContentDialog);
                            }
                        }
                    }
                }
                break;
        }
    }

    /**
     * 跳转到扫一扫页面
     *
     * @param bundle
     */
    public void skipToSqCode(Bundle bundle) {
        if (null == bundle) {
            bundle = new Bundle();
        }
        /*ZxingConfig是配置类
         *可以设置是否显示底部布局，闪光灯，相册，
         * 是否播放提示音  震动
         * 设置扫描框颜色等
         * 也可以不传这个参数
         * */
        ZxingConfig config = new ZxingConfig();
        config.setPlayBeep(true);//是否播放扫描声音 默认为true
        config.setShake(true);//是否震动  默认为true
        config.setDecodeBarCode(true);//是否扫描条形码 默认为true
        config.setReactColor(R.color.main_color);//设置扫描框四个角的颜色 默认为白色
        config.setFrameLineColor(R.color.main_color);//设置扫描框边框颜色 默认无色
        config.setScanLineColor(R.color.main_color);//设置扫描线的颜色 默认白色
        config.setFullScreenScan(true);//是否全屏扫描  默认为true  设为false则只会在扫描框中扫描

        bundle.putSerializable(Constant.INTENT_ZXING_CONFIG, config);
        openActivity(CaptureActivity.class, bundle, REQUEST_CODE_SCAN);
    }


    /**
     * 设置界面全屏
     */
    public void setFullScreen() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    /**
     * 添加fragment到activity
     *
     * @param viewId       fragment填充的位置
     * @param baseFragment 填充的对象
     */
    protected void addFragment(int viewId, BaseFragment baseFragment) {
        try {
            if (null == baseFragment || baseFragment.equals(mCurrentBaseFragment)) {
                return;
            }

            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

            // 隐藏已显示的Fragment
            if (null != mCurrentBaseFragment) {
                fragmentTransaction.hide(mCurrentBaseFragment);
            }

            if (baseFragment.isAdded()) {
                fragmentTransaction.show(baseFragment);
            } else {
                fragmentTransaction.add(viewId, baseFragment, baseFragment.getClass().getSimpleName());
            }
            fragmentTransaction.commitAllowingStateLoss();
            mCurrentBaseFragment = baseFragment;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回
     */
    public void doBack(View view) {
        onBackPressed();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick()) {
                return true;
            }
            if (isRefreshing) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 防止重复点击
     *
     * @return
     */
    protected boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 400) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    public void skipToWeb(String url) {
        Bundle bundle = new Bundle();
        bundle.putString(ConstData.URL, url);
        openActivity(WebActivity.class, bundle, 0);
    }

    public void skipToForgetPs(String pageType) {
        Bundle bundle = new Bundle();
        bundle.putString(ConstData.PAGETYPE, pageType);
        openActivity(ForgetPasswordActivity.class, bundle, 0);
    }

    @SuppressLint("InlinedApi")
    protected void setImmerseLayout() {
        setImmerseLayout(null, null);
    }

    @SuppressLint("InlinedApi")
    protected void setImmerseLayout(View parentView, View childView) {
        setImmerseLayout(parentView, childView, true);
    }

    @SuppressLint("InlinedApi")
    protected void setImmerseLayout(View parentView, View childView, boolean isDark) {
        fullScreen(this);
        setStatusPaddingAndTextColor(parentView, childView, isDark);
    }

    /**
     * 通过设置全屏，设置状态栏透明
     *
     * @param activity
     */
    private void fullScreen(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
            Window window = activity.getWindow();
            View decorView = window.getDecorView();
            //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            //导航栏颜色也可以正常设置
//                window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }


    private void setStatusPaddingAndTextColor(View parentView, View childView, boolean isDark) {
        //判断版本是5.0以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setBarTitleTextColor(isDark);
            int statusHeight = ScreenUtils.getStatusHeight(this);
            if (null != parentView) {
                ViewGroup.LayoutParams parentParams = parentView.getLayoutParams();
                parentParams.height = statusHeight + getResources().getDimensionPixelOffset(R.dimen.title_bar_home_height_top);
                parentView.setLayoutParams(parentParams);
            }
            if (null != childView) {
                //设置系统栏需要的内偏移
                ScreenUtils.setMargins(childView, 0, statusHeight, 0, 0);
            }
        } else {
            if (null != parentView) {
                ViewGroup.LayoutParams parentParams = parentView.getLayoutParams();
                parentParams.height = getResources().getDimensionPixelOffset(R.dimen.title_bar_home_height_top);
                parentView.setLayoutParams(parentParams);
            }
        }
    }

    /**
     * 设置状态栏字体颜色
     *
     * @param isDark
     */
    protected void setBarTitleTextColor(boolean isDark) {
        if (Build.VERSION.SDK_INT >= 21) {
            //setTranslucentStatus(true);
            // 小米手机沉浸式状态栏黑色透明
            SystemBarTintManager systemBarTintManager = new SystemBarTintManager(this);
            // 设置状态栏的文字颜色
            systemBarTintManager.setStatusBarDarkMode(isDark, this);
            View decorView = getWindow().getDecorView();

            int option;
            if (isDark) {
                option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                //新版miui设黑色文字方法
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            } else {
                option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            }

            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    /**
     * 设置状态栏是否透明
     *
     * @param on
     */
    @TargetApi(19)
    protected void setTranslucentStatus(boolean on) {
        Window win = getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }

    public static void setWindowStatusBarColor(Activity activity, int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     *
     */
    @Override
    public void finish() {
        // 判断是否返回MainActivity
        if (!isExitLogin && !(this instanceof MainActivity) && !(this instanceof AlarmTranActivity)
                && !(this instanceof LoginActivity) && !(this instanceof WelcomeActivity)
                && !(this instanceof ForgetPasswordActivity)) {
            if (!Utils.isExistMainActivity(MainActivity.class, this)) {
                openActivity(MainActivity.class);
            }
        }
        super.finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollecter.removeActivity(this);
        DialogUtils.closeDialog(sqCodeContentDialog);
     /*   if(EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }*/
     SpUtils.putString(BaseActivity.this,"","StreamUrl");
    }
}
